<template>
  <view class="flex-col justify-start page">
    <view v-if="isLoading" class="flex justify-center items-center mt-12">
      <text>加载中...</text>
    </view>
    <view v-else class="flex-col items-start" style="width: 100%;">
      <!-- 显示视频 -->
      <video 
        class="media" 
        :src="detail.videoUrl" 
        controls
        @ended="addCheckinRecord(detail.videoId)"
      ></video>
      
      <!-- 标题和简介 -->
      <view class="content-section">
        <text class="title">{{ detail.title }}</text>
        <text class="content">{{ detail.content }}</text>
        <text class="date">{{ detail.date }}</text>
      </view>

      <!-- 评论输入框 -->
      <view class="comment-input">
        <input 
          v-model="newComment" 
          placeholder="请输入评论内容" 
          class="input-field"
        />
        <button @click="submitComment" class="send-button">发送</button>
      </view>

      <!-- 评论列表 -->
      <view class="comment-list">
        <feedback-card 
          v-for="comment in comments" 
          :key="comment.id"
          :comment="comment" 
          @like="handleLike"
          @delete="handleDelete"
        ></feedback-card>
      </view>
    </view>
  </view>
</template>

<script>
import FeedbackCard from '../../components/FeedbackCard/FeedbackCard.vue';

export default {
  components: {
    FeedbackCard,
  },
  props: {},
  data() {
    return {
      detail: {
        videoUrl: "", // 视频 URL
        title: "",
        content: "",
        date: "",
        videoId: null, // 新增：存储视频 ID
      },
      isLoading: true,
      newComment: "", // 用户输入的新评论
      comments: [], // 评论列表
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的评论数量
    };
  },
  methods: {
    fetchDetail(videoId) {
      const url = "/train/video/get/";
      this.$request({
        url: url,
        method: "GET",
        data: {
          video_id: videoId,
        },
        success: (response) => {
          if (response.statusCode === 200) {
            const data = response.data;
            this.detail = {
                videoUrl: data.file_url, // 视频路径
                title: data.title,
                content: data.description,
                date: new Date(data.create_date).toLocaleDateString(),
                videoId: videoId,
            };
            this.fetchComments(videoId); // 初始化时获取评论
          } else {
            console.error("获取视频详情失败");
          }
          this.isLoading = false;
          console.log(this.detail);
        },
        fail: (error) => {
          console.error("请求失败", error);
          this.isLoading = false;
        },
      });
    },
    // 获取评论列表
    fetchComments(videoId) {
      this.$request({
        url: "/train/feedback/get/",
        method: "GET",
        data: {
          video_id: videoId,
          batch_num: this.currentPage,
          batch_size: this.pageSize,
        },
        success: (response) => {
          if (response.statusCode === 200) {
            const comments = Array.isArray(response.data) ? response.data : [];
            this.comments = comments.map(comment => ({
              ...comment,
              is_liked: comment.is_liked,
              like_count: comment.like_count,
              nickname: comment.nickname,
              content: comment.content,
              create_date: comment.create_date,
            }));
          } else {
            console.error("获取评论失败");
          }
        },
        fail: (error) => {
          console.error("获取评论请求失败", error);
        },
      });
    },
    // 提交评论
    submitComment() {
      if (!this.newComment.trim()) {
        uni.showToast({
          title: "评论内容不能为空",
          icon: "none",
        });
        return;
      }
      this.$request({
        url: "/train/feedback/add/",
        method: "POST",
        data: {
          video_id: this.detail.videoId,
          content: this.newComment,
        },
        success: (response) => {
          if (response.statusCode === 200) {
            uni.showToast({
              title: "评论成功",
              icon: "success",
            });
            this.newComment = "";
            this.fetchComments(this.detail.videoId); // 刷新评论列表
          } else {
            console.error("提交评论失败");
          }
        },
        fail: (error) => {
          console.error("提交评论请求失败", error);
        },
      });
    },
    // 点赞评论
    handleLike(commentId) {
      const comment = this.comments.find(c => c.id === commentId);
      if (!comment) return;

      // 先更新本地状态
      comment.is_liked = !comment.is_liked;
      comment.like_count += comment.is_liked ? 1 : -1;

      // 发送请求到后端
      this.$request({
        url: "/train/feedback/like/",
        method: "POST",
        data: {
          feedback_id: commentId,
        },
        success: (response) => {
          if (response.statusCode !== 200) {
            // 如果后端请求失败，回滚本地状态
            comment.is_liked = !comment.is_liked;
            comment.like_count += comment.is_liked ? -1 : 1;
            console.error("点赞失败");
          }
        },
        fail: (error) => {
          // 如果请求失败，回滚本地状态
          comment.is_liked = !comment.is_liked;
          comment.like_count += comment.is_liked ? -1 : 1;
          console.error("点赞请求失败", error);
        },
      });
    },
    // 新增：处理删除事件
    handleDelete(commentId) {
      // 从评论列表中移除被删除的评论
      this.comments = this.comments.filter(comment => comment.id !== commentId);
    },
    addCheckinRecord(videoId) {
      this.$request({
        url: "/train/record/add/",
        method: "POST",
        data: {
          video_id: videoId,
        },
        success: (response) => {
          if (response.statusCode === 200) {
            if (response.data === "success") {
              console.log("打卡成功");
            } else if (response.data === "User has already checked this video in today") {
              console.log("今天已打卡该视频");
            }
          } else {
            console.error("打卡失败", response);
          }
        },
        fail: (error) => {
          console.error("打卡请求失败", error);
        },
      });
    },
  },
  onLoad(options) {
    const { videoId } = options;
    if (videoId) {
      console.log("接收到的参数:", { videoId }); // 调试日志
      this.fetchDetail(videoId);
    } else {
      console.error("缺少必要参数 videoId");
    }
  },
};
</script>

<style scoped lang="css">
.page {
  background-color: #f5f5f5;
}

.media {
  width: 100%;
  height: 400rpx;
  border-radius: 0;
  margin: 0;
}

.content-section {
  padding: 30rpx;
  width: 100%;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #000000;
  margin-bottom: 10rpx;
}

.content {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 10rpx;
}

.date {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 20rpx;
}

.comment-input {
  display: flex;
  align-items: center;
  padding: 0 30rpx 20rpx 30rpx;
  width: 100%;
  box-sizing: border-box;
}

.input-field {
  flex: 1;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  background-color: #fff;
}

.send-button {
  padding: 20rpx 30rpx;
  background-color: #F26A77;
  color: white;
  border-radius: 8rpx;
  border: none;
  font-size: 28rpx;
  white-space: nowrap;
}

.comment-list {
  padding: 0 30rpx 30rpx 30rpx;
  width: 100%;
  box-sizing: border-box;
}
</style>